//
//  Release_ActivityChange.m
//  HappyStore
//
//  Created by 李小辉 on 16/6/15.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "Release_ActivityChange.h"
#import "MapViewController.h"

@interface Release_ActivityChange ()
@property (weak, nonatomic) IBOutlet UIButton *sendFubu;
@property (weak, nonatomic) IBOutlet UITextField *titleTextField;
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UIButton *adressBtn;
@property (weak, nonatomic) IBOutlet UITextField *sponsorTextField;

@property (weak, nonatomic) IBOutlet UILabel *disActLabel;
@property (strong, nonatomic) NSMutableArray *imageAry;//图片
@property (weak, nonatomic) IBOutlet UIButton *startTimeBtn;
@property (weak, nonatomic) IBOutlet UIButton *endTimeBtn;
@property (weak, nonatomic) IBOutlet UIImageView *imagePhoto;
//标签
@property (weak, nonatomic) IBOutlet UILabel *labelLabel;
@property (strong, nonatomic) NSMutableArray *labelAry;
@property (weak, nonatomic) IBOutlet UIButton *disActBtn;
@property (weak, nonatomic) IBOutlet UIButton *imageBtn;
@property (assign, nonatomic) BOOL selectStartAndEndDate;


//地区
@property (strong, nonatomic) NSString *provinceStr;
@property (strong, nonatomic) NSString *cityStr;
@property (strong, nonatomic) NSString *districtStr;
@property (strong, nonatomic) SelectedAddress *selectAddress;//选择地区
@end

@implementation Release_ActivityChange

- (NSMutableArray *)imageAry{
    if (!_imageAry) {
        _imageAry = [NSMutableArray array];
    }
    return _imageAry;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = NO;
    navBarHairlineImageView.alpha = 0.5f;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = YES;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"发布活动";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    //取消返回的描述
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    [[NSNotificationCenter defaultCenter]  addObserver:self
                                              selector:@selector(StartShaiXuanSearch:) name:@"miaoshu"
                                                object:nil];
     
     //监听标签
    [[NSNotificationCenter defaultCenter]  addObserver:self
                                              selector:@selector(labelVCchange:) name:@"biaoqian"
                                                object:nil];
    //地址
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addressMapView:) name:@"mapAddress" object:nil];
//    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(btnClickRight)];
//    self.navigationItem.rightBarButtonItem = rightBar;
    //发布按钮事件
    [self.sendFubu addTarget:self action:@selector(btnClickRight:) forControlEvents:UIControlEventTouchUpInside];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}
-(void)StartShaiXuanSearch:(NSNotification *)dic{
   NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];
    self.imageAry = [NSMutableArray arrayWithArray:muDicParameters[@"images"]];
    self.disActLabel.text = muDicParameters[@"string"];
}
//地址
-(void)addressMapView:(NSNotification *)dic{
    NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];
    self.addressLabel.text = muDic[@"address"];
    self.provinceStr = muDic[@"province"];
    self.cityStr = muDic[@"city"];
    self.districtStr = muDic[@"district"];
    
}

//接收标签
-(void)labelVCchange:(NSNotification *)dic{
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];
    self.labelAry = muDicParameters[@"biaoqian"];
    NSString *string = @"";
    for (NSString *str in self.labelAry) {
         string = [string stringByAppendingString:[NSString stringWithFormat:@"%@,",str]];
    }
    self.labelLabel.text = [string substringWithRange:NSMakeRange(0, [string length]-1)];
    
    
    
    
}
-(void)leftBarButtonItemClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//选择海报图片
- (IBAction)clickImageBtn:(id)sender {

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"照片选择"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相机",@"相册", nil];
    
    [actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    pickerImage.delegate = self;
    pickerImage.allowsEditing = YES;//设置可编辑
    switch (buttonIndex) {
        case 0:
        {
            //NSLog(@"相机");
            pickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 1:
        {
            //NSLog(@"相册");
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 2:
        {
            //NSLog(@"取消");
        }
            break;
    }
    
}
//点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self.imageBtn setTitle:@"" forState:UIControlStateNormal];
    
    [self.imagePhoto setImage:image];
    
}
//点击cancel 调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}
//选择地区
- (IBAction)clickAdressBtn:(id)sender {
//    self.selectAddress = [SelectedAddress sharedSelectedAddress];
//    self.selectAddress.delegatee = self;
//    [self.selectAddress btnClickAddress];
    MapViewController *mapVC = [[MapViewController alloc] init];
    [self.navigationController pushViewController:mapVC animated:YES];

   
}
- (void)seceltedRowSshowMsg:(NSString *)showMsg andProvince:(NSString *)strProvince andCity:(NSString *)strCity andDistrict:(NSString *)strDistrict
{
    
    self.provinceStr = strProvince;
    self.cityStr = strCity;
    self.districtStr = strDistrict;
    self.addressLabel.text = [NSString stringWithFormat:@"%@%@%@",self.provinceStr,self.cityStr,self.districtStr];
}
//添加标签
- (IBAction)clickLabelBtn:(id)sender {
    LabelVC *labelVC = [[LabelVC alloc] initWithNibName:@"LabelVC" bundle:nil];
    labelVC.titleString = @"个人标签";
    labelVC.hobbyArr = self.labelAry;
    [self.navigationController pushViewController:labelVC animated:YES];
}
#pragma mark -选择开始时间
- (IBAction)clickStartTimeBtn:(id)sender {
    self.selectStartAndEndDate = YES;
    datePickView *dateee = [datePickView sharedSelectedAddress];
    dateee.delegatee = self;
    [dateee btnClickDate];
}
//结束时间
- (IBAction)clickEndTimeBtn:(id)sender {
    self.selectStartAndEndDate = NO;
    datePickView *dateee = [datePickView sharedSelectedAddress];
    dateee.delegatee = self;
    [dateee btnClickDate];
}
- (void)seceltedDate:(NSString *)date{
    if (self.selectStartAndEndDate) {
        self.startTimeLabel.text = date;
    }else
        self.endTimeLabel.text = date;
}
//活动描述
- (IBAction)clickDisActBtn:(id)sender {
    ActivityMiaoshu *miaoshuVC = [[ActivityMiaoshu alloc] initWithNibName:@"ActivityMiaoshu" bundle:nil];
    miaoshuVC.activityMiaoshuStr = self.disActLabel.text;
    [self.navigationController pushViewController:miaoshuVC animated:YES];
    }
#pragma mark 照片的时间名称
- (NSString*)dateString
{
    NSMutableString*string=[[NSMutableString alloc] init];
    NSDate*dayDate=[NSDate date];
    NSDateFormatter*dayFormatter=[[NSDateFormatter alloc] init];
    [dayFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStrings= [dayFormatter stringFromDate:dayDate];
    NSArray*dayArray=[dateStrings componentsSeparatedByString:@"-"];
    for (int i=0; i<[dayArray count]; i++) {
        [string appendFormat:@"%@",[dayArray objectAtIndex:i]];
    }
    NSDate*timeDate=[NSDate date];
    NSDateFormatter*timeFormatter=[[NSDateFormatter alloc] init];
    [timeFormatter setDateFormat:@"HH:mm:ss:SSS"];
    NSString *timeString= [timeFormatter stringFromDate:timeDate];
    NSArray*timeArray=[timeString componentsSeparatedByString:@":"];
    for (int i=0; i<[timeArray count]; i++) {
        [string appendFormat:@"%@",[timeArray objectAtIndex:i]];
    }
    return string;
    
}
#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.1);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}
#pragma mark - 发布
-(void)btnClickRight:(UIButton*)btn{
    
    BOOL isOK = YES;
   
    if (isOK && self.titleTextField.text.length == 0) {
        isOK = NO;
        
        [self showSingleIconBubble:@"请输入活动主题"];

    }
    
    
    
    if (isOK && self.startTimeLabel.text.length == 0) {
        isOK = NO;
        [self showSingleIconBubble:@"请选择活动开始时间"];

    }
    
    if (isOK && self.endTimeLabel.text.length == 0) {
        isOK = NO;
        [self showSingleIconBubble:@"请选择活动结束时间"];

    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *startTime = [dateFormatter dateFromString:self.startTimeLabel.text];
    NSDate *endTime = [dateFormatter dateFromString:self.endTimeLabel.text];
    //NSLog(@"%@,%@",startTime,endTime);
    NSComparisonResult *result = [startTime compare:endTime];
    if (isOK && result != NSOrderedAscending) {
        isOK = NO;
        [self showSingleIconBubble:@"开始大于结束时间"];
    }
    
    if (isOK && [self.addressLabel.text isEqualToString:@"请选择活动地点"]) {
        isOK = NO;
        [self showSingleIconBubble:@"请填写活动地点"];

    }
 
    
    if (isOK && [self.labelLabel.text isEqualToString:@"添加标签"]) {
        isOK = NO;
         [self showSingleIconBubble:@"请填写标签"];
    }
    
    if (isOK && ([self.disActLabel.text isEqualToString:@"请输入活动内容及流程"]||[self.disActLabel.text isEqualToString:@"点击填写"] || [self.disActLabel.text isEqualToString:@""])) {
        isOK = NO;
        [self showSingleIconBubble:@"请输入详细信息"];

    }
    
    if (isOK && self.sponsorTextField.text.length == 0 ) {
        isOK = NO;
        [self showSingleIconBubble:@"请填写主办单位"];
    }
    
    if (isOK && self.imagePhoto.image == nil) {
        isOK = NO;
         [self showSingleIconBubble:@"请填写海报"];

    }
    
    
    if (isOK) {
        //暂停用户交互
        btn.userInteractionEnabled = NO;
        //token=验证账户&userId=用户id&useType=用户类型&title=标题&qualityName=行业&money=金额&provinceName=省市&cityName=城市&areaName=区县&lable=标签&description=描述&startTime=活动开始时间 格式：2016-01-16 08:00&endTime=活动结束时间 格式：2016-01-19 18:00 参数：photo-为logo缩略图、photos-为图片zip包
        [self showRoundProgressWithTitle:@"请稍后..."];
        NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"usertype"] forKey:@"useType"];//用户类型
        [muDicParameters setObject:@"0" forKey:@"money"];
        [muDicParameters setObject:self.titleTextField.text forKey:@"title"];
        
        [muDicParameters setObject:self.provinceStr forKey:@"provinceName"];//省市
        [muDicParameters setObject:self.cityStr forKey:@"cityName"];
        [muDicParameters setObject:self.districtStr forKey:@"areaName"];
        
        [muDicParameters setObject:self.disActLabel.text forKey:@"description"];
        [muDicParameters setObject:self.sponsorTextField.text forKey:@"sponsor"];
        [muDicParameters setObject:self.startTimeLabel.text forKey:@"startTime"];//活动开始时间
        [muDicParameters setObject:self.endTimeLabel.text forKey:@"endTime"];//活动开始时间
        //标签
        [muDicParameters setObject:self.labelLabel.text forKey:@"lable"];

        NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"addActivity_app_activity.im.lensum"];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
        [manager POST:strURl parameters:muDicParameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSData *imageData = UIImageJPEGRepresentation(self.imagePhoto.image, 0.5);
            [formData appendPartWithFileData:imageData name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
            //压缩
            NSMutableArray *aryImage = [NSMutableArray arrayWithArray:self.imageAry];
            NSMutableArray *muSaveFull = [NSMutableArray array];
            for (int i = 0; i < aryImage.count; i++) {
                UIImage *image = aryImage[i];
                NSString *strName1 = [NSString stringWithFormat:@"%@.png",[self dateString]];
                [self saveImage:image withName:strName1];
                NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:strName1];
                [muSaveFull addObject:fullPath1];
            }
            //压缩文件路径
            NSString *zippedPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",[self dateString]]];
            BOOL isSucee = [SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:muSaveFull];
            if (isSucee) {
                NSData *data1 = [NSData dataWithContentsOfFile:zippedPath];
                [formData appendPartWithFileData:data1 name:@"photos" fileName:@"photos.zip" mimeType:@"zip"];
            }
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
            btn.userInteractionEnabled = YES;
            if ([dicInfo[@"result"] integerValue] ==1) {
                [self hideBubble];
                //iOS8.0+
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                               message:@"为了保证平台的质量，您的活动会在我们审核通过后展示！"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                                      handler:^(UIAlertAction * action) {
                                                                          [self.navigationController popViewControllerAnimated:YES];}];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else {

                [self showSingleIconBubble:dicInfo[@"msg"]];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            btn.userInteractionEnabled = YES;
            [self showSingleIconBubble:error.localizedDescription];

        }];
    }
}
@end
